<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\code\admin\controller;

use onekey\File;
use think\facade\View;
use app\admin\BaseController;
use app\admin\model\Config;
/**
 * 主题代码编辑器
 */
class Index extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        $config = Config::getVal('app_code');
        $this->path = empty($config) ? root_path() . 'public/themes' : root_path() . $config['path']; // 配置对应路径
    }

	/**
	 * 主页
	 */
    public function index()
    {
        if ($this->request->isPost()) {
            $fileList = $this->scandir($this->path);
        	return json(['status' => 'success', 'message' => '请求成功', 'data' => $fileList]);
        } else {
            return View::fetch();
        }
    }

    /**
     * 查看文件内容
     */
    public function content() 
    {
    	if ($this->request->isPost()) {
    		$input = input('post.');
    		$data  = file_get_contents($input['filePath']);
    		return json(['status' => 'success', 'message' => '请求成功', 'data' => $data]);
    	}
    }

    /**
     * 文件内容修改
     */
    public function update()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            $update = File::create($input['filePath'], $input['content']);
            if ($update) {
                return json(['status' => 'success', 'message' => '修改成功']);
            } else {
                return json(['status' => 'error', 'message' => '修改失敗，文件权限不足']);
            }
        }
    }

    /**
     * 文件删除
     */
    public function delete()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            if ($input['fileType'] === 'folder') {
                $delete = File::delDirAndFile($input['filePath']);
            } else {
                $delete = unlink($input['filePath']);
            }
            if ($delete) {
                return json(['status' => 'success', 'message' => '删除成功']);
            } else {
                return json(['status' => 'error', 'message' => '删除失敗，文件权限不足']);
            }
        }
    }

    /**
     * 文件重命名
     */
    public function rename()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            $path = str_replace($input['oldname'], '', $input['filePath']);
            $update = rename($path.$input['oldname'], $path.$input['newname']);
            if ($update) {
                $data['path'] = $path.$input['newname'];
                $data['newname'] = $input['newname'];
                return json(['status' => 'success', 'message' => '修改成功', 'data' => $data]);
            } else {
                return json(['status' => 'error', 'message' => '修改失敗，文件权限不足']);
            }
        }
    }

    /**
     * 新建文件
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            $path = empty($input['filePath']) ? $this->path.'/' : $input['filePath'];
            $path = $path.$input['fileName'];
            if ($input['fileType'] === 'folder') {
                $save = File::dirMkdir($path);
            } else {
                $save = File::create($path, '');
            }
            if ($save) {
                $data['path'] = $path;
                $data['type'] = $this->fileType($path);
                return json(['status' => 'success', 'message' => '新建成功', 'data' => $data]);
            } else {
                return json(['status' => 'success', 'message' => '新建失敗，文件权限不足']);
            }
            
        }
    }

    /**
     * 返回文件/文件夹列表
     * @param  [string] $fileName 
     */
    public function fileType($fileName) {
        // 基本信息
        $suffix = pathinfo($fileName);
        $mime   = mime_content_type($fileName);
        if (! isset($suffix['extension'])) {
            $suffix = $mime === 'directory' ? 'folder' : $mime;
        } else {
            $suffix = $mime === 'directory' ? 'folder' : $suffix['extension'];
        }
        $type = $suffix;
        switch ($suffix) {
            case 'png':
            case 'jpg':
            case 'gif':
                $type = "image";
                break;
            case 'js':
                $type = "javascript";
                break;
        }
        return $type;
    }

    /**
     * 返回文件/文件夹列表
     * @param  [string] $dir 
     */
    public function scandir($dir){
        //定义一个数组
        $files = array();
        //检测是否存在文件
        if (is_dir($dir)) {
            //打开目录
            if ($handle = opendir($dir)) {
            	$key = -1;
                //返回当前文件的条目
                while (($file = readdir($handle)) !== false) {
                    //去除特殊目录
                    if ($file != "." && $file != "..") {
                    	$key++;
                        //判断子目录是否还存在子目录
                        if (is_dir($dir . "/" . $file)) { 
                            $files[$key]['children'] = $this->scandir($dir . "/" . $file);
                        } else {
                            $files[$key]['children'] = [];
                        }
                        // 基本信息
                        $fileName = $dir . "/" . $file; 
                        $type = $this->fileType($fileName);
                        $sort = $type === 'folder' ? '0' : $type;
                        $files[$key]['sort'] = $sort;
                        $files[$key]['type'] = $type;
                        $files[$key]['name'] = $file;
                        $files[$key]['path'] = $dir . "/" . $file;
                        $files[$key]['content'] = '';
                        $files[$key]['isNew'] = false;
                        $files[$key]['saveLoading'] = false;
                        $files[$key]['isSave'] = true;
                        $files[$key]['rename'] = false;
                        $files[$key]['newname'] = $file;
                    }
                }
                $order_sort = array_column($files,'sort');
                $order_name = array_column($files,'name');
				array_multisort($order_sort,SORT_ASC,$order_name,SORT_ASC,$files);
                //关闭文件夹
                closedir($handle);
                //返回文件夹数组
                return $files;
            }
        }
    }
}